package com.talkology.pilot.manager.util;


import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;

public class ManagementUtil {
    private static final Logger LOG = LoggerFactory.getLogger(ManagementUtil.class);

    /**
     * 输入自己的id跟密码，获取微信的安全密令字符串
     *
     * @param appid appid
     * @param secret secret
     * @return access token
     */
    public static String getAccessToken(String appid, String secret) {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                + appid + "&secret=" + secret;
        String accessToken = null;
        try {
            //设置链接
            URL urlGet = new URL(url);
            //设置外网代理链接
            InetSocketAddress addr = new InetSocketAddress("192.168.99.100", 80);
            Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
            HttpURLConnection http = (HttpURLConnection) urlGet.openConnection(proxy);
            http.setRequestMethod("GET");
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
            System.setProperty("sun.net.client.defaultReadTimeout", "30000");
            //链接
            http.connect();
            //获取返回值json字节流
            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            //转化成字符串
            String message = new String(jsonBytes, MConstants.UTF_8);
            //转化成json对象然后返回accessToken属性的值
            JSONObject demoJson = JSONObject.parseObject(message);
            accessToken = demoJson.getString(MConstants.ACCESS_TOKEN);
            System.out.println(accessToken);
            is.close();
        } catch (Exception e) {
            LOG.error("Exception when get access token. {}", e);
        }
        return accessToken;
    }

}

